package com.hzhq.contract.service.impl;

import com.hzhq.contract.bean.dto.CompanyDTO;
import com.hzhq.contract.bean.dto.DepartDTO;
import com.hzhq.contract.bean.entity.Company;
import com.hzhq.contract.bean.entity.Depart;
import com.hzhq.contract.bean.entity.Role;
import com.hzhq.contract.convert.CompanyConvertBasic;
import com.hzhq.contract.convert.DepartConvertBasic;
import com.hzhq.contract.repo.CompanyRepository;
import com.hzhq.contract.service.CompanyService;
import com.hzhq.contract.status.DefaultValue;
import com.hzhq.contract.util.Page2ResultUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: hzhq1255
 * @mail: hzhq1255@163.com
 * @date: 2021/4/15 0:14
 * @desc:
 */
@Service
public class CompanyServiceImpl implements CompanyService {


    @Autowired
    CompanyRepository companyRepo;

    @Autowired
    MongoTemplate mongoTemplate;

    private Boolean isExisted(String name){
        Optional<Company> companyOptional = companyRepo.findByCompanyNameAndDeleted(name, DefaultValue.NOT_DELETED);
        return companyOptional.isPresent();
    }

    private Boolean isExisted(ObjectId id){
        Optional<Company> companyOptional = companyRepo.findByCompanyIdAndDeleted(id,DefaultValue.NOT_DELETED);
        return companyOptional.isPresent();
    }

    @Override
    public List<CompanyDTO> getAllList() {
        List<Company> companyList = companyRepo.findByDeleted(DefaultValue.NOT_DELETED);
        return companyList.stream().map(CompanyConvertBasic.INSTANCE::poToDto).collect(Collectors.toList());
    }

    @Override
    public Page<CompanyDTO> getAllPage(Integer currentPage, Integer pageSize) {
        Pageable pageable = Page2ResultUtil.buildPageableByParam(currentPage, pageSize,
                Sort.by(Sort.Direction.DESC,"companyId"));
        Page<Company> companyPage = companyRepo.findByDeleted(DefaultValue.NOT_DELETED,pageable);
        return companyPage.map(CompanyConvertBasic.INSTANCE::poToDto);
    }

    @Override
    public Page<CompanyDTO> searchAllPageByQuery(Query query, Integer currentPage, Integer pageSize) {
        Pageable pageable = Page2ResultUtil.buildPageableByParam(currentPage, pageSize, Sort.by(Sort.Direction.DESC, Company.COMPANY_ID_FIELD));
        long count = mongoTemplate.count(query, Company.class);
        List<Company> companies = mongoTemplate.find(query.with(pageable), Company.class);
        List<CompanyDTO> companyDTOS = companies.stream().map(CompanyConvertBasic.INSTANCE::poToDto).collect(Collectors.toList());
        return new PageImpl<>(companyDTOS, pageable, count);
    }

    @Override
    public CompanyDTO getOneByCompanyName(String companyName) {
        Optional<Company> companyOptional = companyRepo.findByCompanyNameAndDeleted(companyName,DefaultValue.NOT_DELETED);
        return companyOptional.map(CompanyConvertBasic.INSTANCE::poToDto).orElse(null);
    }

    @Override
    public CompanyDTO getOneByCompanyId(String companyId) {
        if (!ObjectId.isValid(companyId)){
            return null;
        }
        Optional<Company> companyOptional = companyRepo.findByCompanyIdAndDeleted(new ObjectId(companyId),DefaultValue.NOT_DELETED);
        return companyOptional.map(CompanyConvertBasic.INSTANCE::poToDto).orElse(null);
    }

    @Override
    public CompanyDTO update(CompanyDTO companyDTO) {
        Optional<Company> companyOptional = companyRepo.findByCompanyIdAndDeleted(companyDTO.getCompanyId(),DefaultValue.NOT_DELETED);
        if (companyOptional.isPresent()){
            Company updateCompany = companyOptional.get();
            Company source = CompanyConvertBasic.INSTANCE.dtoToPo(companyDTO);
            BeanUtils.copyProperties(source,updateCompany);
            updateCompany.setDeleted(DefaultValue.NOT_DELETED);
            return CompanyConvertBasic.INSTANCE.poToDto(companyRepo.save(updateCompany));
        }
        return null;
    }

    @Override
    public CompanyDTO save(CompanyDTO companyDTO) {
        Company company = companyRepo.save(CompanyConvertBasic.INSTANCE.dtoToPo(companyDTO));
        return CompanyConvertBasic.INSTANCE.poToDto(company);
    }

    @Override
    public List<CompanyDTO> saveAll(List<CompanyDTO> companyDTOList) {
        List<Company> company = companyRepo.saveAll(
                companyDTOList.stream().map(CompanyConvertBasic.INSTANCE::dtoToPo).collect(Collectors.toList()));
        return company.stream().map(CompanyConvertBasic.INSTANCE::poToDto).collect(Collectors.toList());
    }

    @Override
    public String deleteById(String companyId) {
        if (ObjectId.isValid(companyId)){
            Optional<Company> companyOptional = companyRepo.findByCompanyIdAndDeleted(new ObjectId(companyId),DefaultValue.NOT_DELETED);
            if (companyOptional.isPresent()){
                Company company = companyOptional.get();
                company.setDeleted(DefaultValue.DELETED);
                companyRepo.save(company);
                return companyId;
            }
        }
        return null;
    }

    @Override
    public String deleteByName(String companyName) {
        Optional<Company> companyOptional = companyRepo.findByCompanyNameAndDeleted(companyName,DefaultValue.NOT_DELETED);
        if (companyOptional.isPresent()){
            Company company = companyOptional.get();
            company.setDeleted(DefaultValue.DELETED);
            companyRepo.save(company);
        }
        return companyOptional.map(e -> e.getCompanyId().toString()).orElse(null);
    }

    @Override
    public List<String> deleteAll(List<String> companyIds) {
        List<ObjectId> objectIds = companyIds.stream().filter(ObjectId::isValid).map(ObjectId::new).collect(Collectors.toList());;
        List<Company> companyList = companyRepo.findByDeletedAndCompanyIdIn(DefaultValue.NOT_DELETED,objectIds).stream()
                .peek(e->e.setDeleted(DefaultValue.DELETED)).collect(Collectors.toList());
        return companyRepo.saveAll(companyList).stream().map(e -> e.getCompanyId().toString()).collect(Collectors.toList());
    }


    @Override
    public Page<CompanyDTO> searchAllPages(CompanyDTO companyDTO, Integer currentPage, Integer pageSize) {
        companyDTO.setDeleted(DefaultValue.NOT_DELETED);
        Company company = CompanyConvertBasic.INSTANCE.dtoToPo(companyDTO);
        Sort sort = Sort.by(new Order(Sort.Direction.DESC,"companyId"));
        Pageable pageable = Page2ResultUtil.buildPageableByParam(currentPage, pageSize,sort);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("companyName",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("address",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("phone",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("email",ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Company> companyExample = Example.of(company,exampleMatcher);
        return companyRepo.findAll(companyExample,pageable).map(CompanyConvertBasic.INSTANCE::poToDto);
    }
}
